package com.itboye.ihomebank.activity.hetong;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.bigkoo.pickerview.OptionsPickerView;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.web.WebActivity;

import java.util.ArrayList;

/**
 * 填写租金信息
 */
public class ActivityEditFangZuXinXi extends BaseOtherActivity {
	View v_statusbar;
	ImageView close_icon;
	TextView add_lift_tv, save, txt_fenqishu;
	ToggleButton toggle_button;
	RelativeLayout xuanzefenqi, bufenqi;
	LinearLayout qishu_container;
	private RelativeLayout layout;
	private PopupWindow mPopWin;
	protected int totalFenQi;
	ArrayList<EditText> arrayListEdit = new ArrayList<>();
	boolean isExpand = true;
	int qishu;
	TextView txt;
	EditText edit;
	private ArrayAdapter adapter;
	String totalDate;
	RelativeLayout shifoutongyi;

	String type;//上个页面的数据   标记是否含有“is_stage”字段，没有type=1 表示没有分期，有type=2 表示有分期
	ToggleButton toggle_fenqi;//选择分期
	boolean isFenQi = false;//是否选择了小贷分期。默认没有选择
	boolean isBank = false;//是否选择了银行分期。默认没有选择
	//小贷分期
	RelativeLayout layout_fenqi;//分期=
	LinearLayout layout_zujin,fenqi;//租金的界面，选择分期的界面
	EditText fenqi_huankuan;//分期的金额
	RelativeLayout layout_sifang;
	TextView tv_hetong;
	ToggleButton tb_hetong;
	boolean isHetong = true;//是否选择了四方分期


	//银行分期
	RelativeLayout layout_bank;
	ToggleButton bank_fenqi;
	LinearLayout bank;
	TextView bank_huankuan;//分期方式
	EditText bank_je;//还款金额

	private String contractNo;
	private OptionsPickerView pvOptionsZhiFu;
	private ArrayList<String> options1ItemsZhiFu = new ArrayList<>();//支付方式

	private int year;//租期年
	private int month;//租期月
	@Override
	public void onClick(View v) {
		Intent intent = null;

		switch (v.getId()) {
			case R.id.close_icon:
				finish();
				break;
			case R.id.tb_hetong:
				isHetong = !isHetong;
				break;
			case R.id.tv_hetong:
				intent = new Intent(this, WebActivity.class);
				intent.putExtra(
						"url",
						NetPublicConstant.WEB_URL02
								+ "/contract/stageagreement?contract_no="
								+ contractNo
								+"&uid="
								+ (SPUtils.get(this, null, SPContants.USER_ID, "") + "")
								+ "&psw="
								+ (SPUtils.get(this, null,SPContants.PASSWORD, "") + ""));
				intent.putExtra("title", "分期协议");
				startActivity(intent);
				break;
			case R.id.save:
				StringBuffer stringBuffer = new StringBuffer();
				if (isBank){//银行贷款
					if (bank_huankuan.getText().toString().equals("")) {
						ByAlert.alert("请选择分期方式");
						return;
					}
					if (bank_je.getText().toString().equals("")) {
						ByAlert.alert("请输入分期金额");
						return;
					}

					stringBuffer.append(Double.parseDouble(bank_je.getText().toString())*100 + ",");
					intent = new Intent();
					intent.putExtra("date", bank_huankuan.getText().toString().trim());
					intent.putExtra("bank", isBank==true?"是":"否");
					intent.putExtra("fenqi", isFenQi==true?"是":"否");
					intent.putExtra("zujinxinxi",
							stringBuffer.length() > 0 ? stringBuffer.toString()
									.substring(0, stringBuffer.length() - 1) : "");
					setResult(110, intent);
					finish();

				}else {
					if (isFenQi==false) {
						boolean isEmpty = false;
						if (isExpand == false) {// 选择了 不统一分期
							for (int i = 0; i < arrayListEdit.size(); i++) {
								String edit = arrayListEdit.get(i).getText().toString();
								if (edit.equals("")) {
									isEmpty = true;
									break;
								} else {
									stringBuffer.append(Double.parseDouble(edit)*100 + ",");
								}
							}

							if (isEmpty) {
								ByAlert.alert("请将租金信息输入完整");
								return;
							}
						} else {

							if (edit.getText().toString().equals("")) {
								ByAlert.alert("请输入每年应付的金额");
								return;
							}
							for (int i = 0; i < totalFenQi; i++) {

								stringBuffer.append(Double.parseDouble(edit.getText().toString())*100 + ",");
							}
						}

					}else{
						if (fenqi_huankuan.getText().toString().equals("")) {
							ByAlert.alert("请输入分期金额");
							return;
						}
						if (isHetong == false) {
							ByAlert.alert("你还没有同意四方分期合同");
							return;
						}
						stringBuffer.append(Double.parseDouble(fenqi_huankuan.getText().toString())*100 + ",");
					}

					System.out.println(stringBuffer.toString() + "________>");
					intent = new Intent();
					intent.putExtra("zujinxinxi",
							stringBuffer.length() > 0 ? stringBuffer.toString()
									.substring(0, stringBuffer.length() - 1) : "");
					intent.putExtra("fenqi", isFenQi==true?"是":"否");
					intent.putExtra("bank", isBank==true?"是":"否");
					setResult(106, intent);
					finish();
				}

				break;
			case R.id.xuanzefenqi:
				// chuzuPopWindow(v);
				break;
			case R.id.toggle_button:
				if (isExpand) {
					if (totalFenQi == 0) {
						ByAlert.alert("请先选择分期");
						return;
					}
					bufenqi.setVisibility(View.GONE);
					fenqi(totalFenQi);
				} else {
					edit.setInputType(InputType.TYPE_CLASS_NUMBER);
					txt.setText("请输入每期租金:");
					edit.setHint("请输入每期租金");
					bufenqi.setVisibility(View.VISIBLE);
					qishu_container.removeAllViews();
					arrayListEdit.clear();
				}

				isExpand = !isExpand;
				break;
			case R.id.toggle_fenqi://小贷
				if (isFenQi) {
					if (!isBank){//没选择小贷也没选择银行
						layout_zujin.setVisibility(v.VISIBLE);
					}
					fenqi.setVisibility(v.GONE);
				}else{
					layout_zujin.setVisibility(v.GONE);
					fenqi.setVisibility(v.VISIBLE);
					if (isBank){
					isBank=!isBank;
					bank_fenqi.setChecked(isBank);
					bank.setVisibility(v.GONE);
				}
				}
				isFenQi = !isFenQi;
				break;

			case R.id.bank_fenqi://银行
				if (isBank) {
					if (!isFenQi){//没选择小贷也没选择银行
						layout_zujin.setVisibility(v.VISIBLE);
					}
					bank.setVisibility(v.GONE);
				}else{
					layout_zujin.setVisibility(v.GONE);
					bank.setVisibility(v.VISIBLE);
					//显示分期选择相 当大于1年时有选择
					pvOptionsZhiFu.show();
					if (isFenQi){
					isFenQi=!isFenQi;
					toggle_fenqi.setChecked(isFenQi);
					fenqi.setVisibility(View.GONE);
				}
				}
				isBank = !isBank;

				break;
			default:
				break;
		}
	}


	private void fenqi(int totalFenQi) {
		// TODO Auto-generated method stub
		qishu_container.removeAllViews();
		for (int i = 0; i < totalFenQi; i++) {
			View view = LayoutInflater.from(this).inflate(R.layout.item_hetong,
					null);
			LayoutParams layoutParams = new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
			layoutParams.setMargins(0, 5, 0, 5);
			TextView textView = (TextView) view.findViewById(R.id.txt);
			textView.setText("第" + (i + 1) + "年月租金");

			EditText edt = (EditText) view.findViewById(R.id.edit);
			edt.setInputType(InputType.TYPE_CLASS_NUMBER);
			edt.setTextSize(16);
			arrayListEdit.add(edt);
			edt.setHint("输入第" + (i + 1) + "年月租金");
			qishu_container.addView(view, layoutParams);
		}
	}


	@Override
	protected int layout_id() {
		// TODO Auto-generated method stub
		return R.layout.activity_hetong_fangzuxinxi;
	}

	@Override
	protected void onInitController() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void onInit() {
		setStatusBarHeight(v_statusbar);
		contractNo = getIntent().getStringExtra("contractNo");
		type= getIntent().getStringExtra("type");
		if (type!=null){
			if (type.equals("2")){
				layout_fenqi.setVisibility(View.VISIBLE);
				layout_bank.setVisibility(View.VISIBLE);
			}else{
				layout_fenqi.setVisibility(View.GONE);
				layout_bank.setVisibility(View.GONE);
			}
		}

		totalDate = getIntent().getStringExtra("totalDate");

		String[] tempDate=null;
		if(totalDate!=null){
			tempDate = totalDate.split("-");
		}
		String str="";
		if(tempDate!=null){
			str = tempDate[0] + "年" + tempDate[1] + "月" + tempDate[2] + "天";
            year=Integer.parseInt(tempDate[0].trim());
            month=Integer.parseInt(tempDate[1].trim());
			if (!tempDate[0].equals("0") && !tempDate[1].equals("0")// 年月日
					&& !tempDate[2].equals("0")) {
				str =  tempDate[0] + "年" + tempDate[1] + "月" + tempDate[2]
						+ "天";
			} else if (tempDate[0].equals("0") && !tempDate[1].equals("0")// 月日
					&& !tempDate[2].equals("0")) {
				str =  tempDate[1] + "月" + tempDate[2] + "天";
			} else if (!tempDate[0].equals("0") && tempDate[1].equals("0")// 年日
					&& !tempDate[2].equals("0")) {
				str =  tempDate[0] + "年" + tempDate[2] + "天";
			} else if (tempDate[0].equals("0") && tempDate[1].equals("0")// 日
					&& !tempDate[2].equals("0")) {
				str =  tempDate[2] + "天";
			} else if (!tempDate[0].equals("0") && !tempDate[1].equals("0")// 年月
					&& tempDate[2].equals("0")) {
				str =  tempDate[0] + "年" + tempDate[1] + "月";
			} else if (tempDate[0].equals("0") && !tempDate[1].equals("0")// 月
					&& tempDate[2].equals("0")) {
				str =  tempDate[1] + "月";
			} else if (!tempDate[0].equals("0") && tempDate[1].equals("0")// 年
					&& tempDate[2].equals("0")) {
				str =  tempDate[0] + "年";
			}
		}

//		if (year>0){
		options1ItemsZhiFu.add("合同期一年,用户分11期");
		options1ItemsZhiFu.add("合同期一年,用户半年分两次5期");
		options1ItemsZhiFu.add("合同期半年,用户分5期");
        initOptionPicker();
//		}else if (month>=6){
//			bank_huankuan.setText("分5期");
//		}else {
//			layout_bank.setVisibility(View.GONE);
//		}
		txt_fenqishu.setText(str);
		edit.setInputType(InputType.TYPE_CLASS_NUMBER);
		txt.setText("请输入每年月租金:");
		edit.setHint("请输入每年月租金");
		save.setVisibility(View.VISIBLE);
		save.setTextSize(16);
		add_lift_tv.setText("填写房租信息");
		qishu = getIntent().getIntExtra("qishu", 0);
		if (qishu == 0) {
			qishu=1;
		}

//		ByAlert.alert(qishu+"");
		totalFenQi = qishu;
	}

	@Override
	protected void onReadIntent(Bundle bundle) {
		// TODO Auto-generated method stub
	}




	/**
	 * 银行分期
	 */
	private void initOptionPicker() {//条件选择器初始化
		/**
		 * 注意 ：如果是三级联动的数据(省市区等)，请参照 JsonDataActivity 类里面的写法。
		 */
		pvOptionsZhiFu = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
			@Override
			public void onOptionsSelect(int options1, int options2, int options3, View v) {
				//返回的分别是三个级别的选中位置
				String tx = options1ItemsZhiFu.get(options1);
				//选择的分期方式
				bank_huankuan.setText(tx);
//				fukuan.setText(tx);
//				fangshi = house_pay.get(options1).getId();
			}
		})
				.setTitleText("付款方式选择")
				.setContentTextSize(16)//设置滚轮文字大小
				.setTitleSize(16)//设置标题文字大小
				.setSubCalSize(16)//设置确定按钮大小
				.setSelectOptions(0, 1)//默认选中项
				.setLineSpacingMultiplier(2.0f)//设置间距倍数,但是只能在1.2-2.0f之间
				.setDividerColor(Color.LTGRAY)//设置分割线的颜色
				.setBgColor(Color.WHITE)//滚轮背景颜色
				.setTitleBgColor(Color.WHITE)//标题背景颜色
				.setTitleColor(Color.BLACK)//标题颜色
				.setCancelColor(Color.BLACK)//取消按钮颜色
				.setSubmitColor(Color.BLACK)//确定按钮颜色
				.setTextColorCenter(Color.BLACK)//分割线之间的文字颜色
				.isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
				.setLabels("", "", "")
				.setBackgroundId(0x66000000) //设置外部遮罩颜色
				.build();
		pvOptionsZhiFu.setPicker(options1ItemsZhiFu);//二级选择器
	}


}